
require 'rubygems'
require 'sinatra'
require 'net/http'
require 'erb'

require 'veegee.rb'
require 'saxon.rb'

helpers do
end

get '/' do
  erb :index
end

# rasterisation of a given SVG document via a given XSL transform
get '/rasterize/*/via/*' do |uri|
  
  puts "rasterize via xslt"

  uri = params[:splat][0]
  via = params[:splat][1]
    
  # create new SVG document
  svg = VeeGee.new uri

  # transform the svg document
  xsl = Saxon.new via
  x = xsl.transform uri, params, "cache/#{svg.cacheKey}.svg"

  # set the svg uri to the transformed xsl & render it
  svg.uri = 'file://' + File.expand_path("cache/#{svg.cacheKey}.svg")
  svg.render "cache/#{svg.cacheKey}.png"

  # read cached image 
  contents = open("cache/#{svg.cacheKey}.png", "rb") {|io| io.read }

  # output
  content_type 'image/png'
  contents
  
end
  
# simple rasterisation of a given SVG document
get '/rasterize/*' do |uri|

  puts "rasterize"

  svg = VeeGee.new uri
  svg.render "cache/#{svg.cacheKey}.png"

  # read cached image 
  contents = open("cache/#{svg.cacheKey}.png", "rb") {|io| io.read }

  # output
  content_type 'image/png'
  contents
end

# returns the key used to cache the rasterized SVG 
get '/key/*' do |uri|

  # create new SVG document
  svg = VeeGee.new uri
  
  # output
  content_type 'text/plain'
  svg.cacheKey
end

# reserved for exploration ...
get '/_test/*' do |uri|

  foo = Saxon.new './xsl/foo.xsl'
  x = foo.transform './samples/box.svg', params

  # output
  content_type 'text/plain'
  x  
end


